from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from sqlalchemy import func
from typing import List
import os
from datetime import date

from ..models import get_db, Contact, Link, LinkCategory, Tag, Title, WebsiteConfig, SearchEngine, VisitStat
from ..templates import templates
from ..config import STATIC_DIR

router = APIRouter()

@router.get("/", response_class=HTMLResponse)
def root(request: Request, db: Session = Depends(get_db)):
    """网站首页"""
    # 记录访问统计
    today = date.today()
    # 查找今天的访问统计记录
    visit_stat = db.query(VisitStat).filter(VisitStat.visit_date == today).first()
    if visit_stat:
        # 如果存在记录，增加访问次数
        visit_stat.visit_count += 1
    else:
        # 如果不存在记录，创建新记录
        visit_stat = VisitStat(visit_date=today, visit_count=1)
        db.add(visit_stat)
    db.commit()
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first() or WebsiteConfig()
    
    # 获取联系信息
    contacts = db.query(Contact).filter(Contact.status == True).all()
    
    # 获取状态为True的链接分类
    link_categories = db.query(LinkCategory).filter(LinkCategory.status == True).all()
    
    # 创建分类ID到名称的映射
    category_map = {cat.id: cat.name for cat in link_categories}
    
    # 获取状态为True的链接，并确保它们属于启用的分类
    links = db.query(Link).filter(Link.status == True).all()
    enabled_links = []
    for link in links:
        # 只为属于启用分类的链接添加category属性
        if link.category_id and link.category_id in category_map:
            link.category = category_map[link.category_id]
            enabled_links.append(link)
        elif not link.category_id:  # 如果链接没有分类，也显示它
            link.category = "其他链接"  # 默认分类名称
            enabled_links.append(link)
    
    # 只使用启用分类中的链接
    links = enabled_links
    
    # 获取标签
    tags = db.query(Tag).filter(Tag.status == True).all()
    
    # 获取标题
    titles = db.query(Title).filter(Title.status == True).all()
    
    # 获取搜索引擎
    search_engines = db.query(SearchEngine).filter(SearchEngine.status == True).all()
    
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            "config": config,
            "contacts": contacts,
            "links": links,
            "tags": tags,
            "titles": titles,
            "search_engines": search_engines
        }
    )

@router.get("/api/public/search-engines")
def get_search_engines(db: Session = Depends(get_db)):
    """获取公共搜索引擎列表"""
    from ..models import SearchEngine
    search_engines = db.query(SearchEngine).filter(SearchEngine.status == True).all()
    return [
        {
            "id": engine.id,
            "name": engine.name,
            "url": engine.url,
            "icon": engine.icon
        }
        for engine in search_engines
    ]

@router.get("/admin", response_class=HTMLResponse)
def admin_dashboard(request: Request, db: Session = Depends(get_db)):
    """后台管理首页"""
    # 获取各项内容的统计信息
    from ..models import SearchEngine, StaticPage
    
    stats = {
        "contacts": db.query(Contact).count(),
        "links": db.query(Link).count(),
        "link_categories": db.query(LinkCategory).count(),
        "tags": db.query(Tag).count(),
        "titles": db.query(Title).count(),
        "search_engines": db.query(SearchEngine).count(),
        "static_pages": db.query(StaticPage).count()
    }
    
    # 导航菜单
    menu_items = [
        {"name": "控制台", "url": "/admin", "icon": "fas fa-tachometer-alt"},
        {"name": "网站配置", "url": "/admin/website-config", "icon": "fas fa-cog"},
        {"name": "联系信息", "url": "/admin/contacts", "icon": "fas fa-address-book"},
        {"name": "链接分类", "url": "/admin/link-categories", "icon": "fas fa-th-large"},
        {"name": "网站链接", "url": "/admin/links", "icon": "fas fa-link"},
        {"name": "标签管理", "url": "/admin/tags", "icon": "fas fa-tags"},
        {"name": "标题管理", "url": "/admin/titles", "icon": "fas fa-heading"},
        {"name": "搜索引擎", "url": "/admin/search-engines", "icon": "fas fa-search"},
        {"name": "静态网页", "url": "/admin/static-pages", "icon": "fas fa-file-alt"}
    ]
    
    return templates.TemplateResponse(
        "admin/dashboard.html",
        {
            "request": request,
            "menu_items": menu_items,
            "stats": stats
        }
    )